/*
 * @Author       : tfhappy
 * @Date         : 2020-07-06 23:47:39
 * @LastEditTime : 2020-07-09 00:29:07
 * @FilePath     : /giteecli/api/auth.go
 * @Description  :
 */
package api

import (
	"net/http"
	"net/url"

	"gitee.com/tfhappy/giteecli/common"
)

type AuthRequest struct {
	Username     string
	Password     string
	ClientID     string
	ClientSecret string
}

type AuthInfo struct {
	common.CommonError
	AccessToken  string `json:"access_token"`
	TokenType    string `json:"token_type"`
	ExpiresIn    int    `json:"expires_in"`
	RefreshToken string `json:"refresh_token"`
	Scope        string `json:"scope"`
	CreatedAt    int    `json:"created_at"`
}

func GetAuthInfo(r *AuthRequest) (*AuthInfo, error) {
	re, err := http.PostForm(common.GiteeAuthURL, url.Values{
		"grant_type":    {"password"},
		"username":      {r.Username},
		"password":      {r.Password},
		"client_id":     {r.ClientID},
		"client_secret": {r.ClientSecret},
		"scope":         {"user_info projects"}, // 权限范围, 空格隔开 user_info projects pull_requests issues notes keys hook groups gists enterprises
	})
	if err != nil {
		return nil, err
	}
	defer re.Body.Close()

	resp := &AuthInfo{}
	err = common.ParseJsonBody(re.Body, resp)
	if err != nil {
		return nil, err
	}
	if !resp.CommonError.IsNil() {
		return nil, resp.CommonError
	}
	return resp, nil
}
